#!/bin/sh

# parameters: <workspace-path> <project-name> <url>

# parameters

if [ $# -ne 3 ]; then
	echo "Usage: bash fossil-client-fetch-repo.sh <workspace-path> <project-name> <url>"
	exit 2
fi

strWorkspacePath=$1
strProjectName=$2
strUrl=$3

cd "$(dirname $(readlink -f "$0"))"
cd ../bin
strFossilPath=`pwd`

function createDirectory()
{
	if [ ! -d "$1" ]; then
		mkdir "$1"
		if [ $? -ne 0 ]; then
			echo "Error: cannot create directory [$1]!"
			return 1;
		fi
	fi
	return 0;
}

createDirectory "$strWorkspacePath/ws"
if [ $? -ne 0 ]; then exit 3; fi
createDirectory "$strWorkspacePath/log"
if [ $? -ne 0 ]; then exit 3; fi

# update

if [ -d "${strWorkspacePath}/ws/${strProjectName}" ]; then
	echo "check update ..."
	cd "${strWorkspacePath}/ws/${strProjectName}/tree"
	echo -e "y\ny\ny\n" | "$strFossilPath/fossil" pull
	if [ $? -ne 0 ]; then
		echo "Error: pull error."
		exit 4
	fi
	sleep 2
	"$strFossilPath/fossil" update > "${strWorkspacePath}/log/pull.txt"
	if [ $? -ne 0 ]; then
		echo "Error: update error."
		exit 5
	fi
	sleep 2
	grep "Already up-to-date" "${strWorkspacePath}/log/pull.txt"
	if [ $? -ne 0 ]; then
		echo "Changed."
		exit 0
	fi
	echo "Unchanged."
	exit 1
fi

# clone

echo "Fetch code ..."

createDirectory "${strWorkspacePath}/ws/${strProjectName}"
if [ $? -ne 0 ]; then exit 3; fi
createDirectory "${strWorkspacePath}/ws/${strProjectName}/repo"
if [ $? -ne 0 ]; then exit 3; fi
createDirectory "${strWorkspacePath}/ws/${strProjectName}/tree"
if [ $? -ne 0 ]; then exit 3; fi

cd "${strWorkspacePath}/ws/${strProjectName}/repo"
echo -e "y\ny\ny\n" | "$strFossilPath/fossil" clone --save-http-password "$strUrl" "${strProjectName}.fossil"
if [ $? -ne 0 ]; then
	echo "Error: clone error."
	exit 6
fi
sleep 2
"$strFossilPath/fossil" setting autosync off -R "${strProjectName}.fossil"
"$strFossilPath/fossil" setting crnl-glob *, -R "${strProjectName}.fossil"
"$strFossilPath/fossil" setting encoding-glob *, -R "${strProjectName}.fossil"
"$strFossilPath/fossil" setting binary-glob *, -R "${strProjectName}.fossil"

cd "${strWorkspacePath}/ws/${strProjectName}/tree"
"$strFossilPath/fossil" open "${strWorkspacePath}/ws/${strProjectName}/repo/${strProjectName}.fossil"
if [ $? -ne 0 ]; then
	echo "Error: open error."
	exit 7
fi
echo "Succeeded."

exit 0
